package upload

import (
	"fmt"
	"github.com/goravel/framework/contracts/filesystem"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"goravel/app/models/systemEntity"
	"path/filepath"
	"time"
)

type UploadService struct {
}

func NewUploadService() *UploadService {
	return &UploadService{}
}
func (*UploadService) Upload(ctx http.Context, file filesystem.File, pid uint) (*systemEntity.SystemAttachment, error) {
	name := file.GetClientOriginalName()
	//extension := file.GetClientOriginalExtension()
	file_type, _ := file.MimeType()
	file_size, _ := file.Size()
	//获取当前年月2022-02
	yearMonth := fmt.Sprintf("%d-%02d", time.Now().Year(), time.Now().Month())
	file_path := filepath.Join("uploads", "attach", yearMonth)

	att_path, err := file.Store(file_path)
	if err != nil {
		return nil, err
	}

	att := systemEntity.SystemAttachment{
		Name:       name,
		AttDir:     filepath.Join("/", att_path),
		SattDir:    filepath.Join("/", att_path),
		AttSize:    file_size,
		AttType:    file_type,
		PID:        pid,
		ImageType:  1,
		ModuleType: 1,
		RealName:   name,
		ScanToken:  "",
	}
	err2 := facades.Orm().Query().Model(&systemEntity.SystemAttachment{}).Create(&att)
	if err != nil {
		return nil, err2
	}
	return &att, nil
}
